package com.atstudy.jdbc;

import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;

/**
 * @version v1.0
 * @description:
 * @author: admin
 * @date: 2023/1/11 9:23
 * @copyright: 博为峰
 */
public class JdbcDemo03 {
    public static void main(String[] args) {
//        query();
        Cla cla = new Cla(1, "110期", 110, new Date());
        insert(cla);
    }

    private static void insert(Cla cla) {
        Connection conn = DBUtils.getConn();
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement("insert into cla (name,num,create_time)values(?,?,?)");
            preparedStatement.setString(1, cla.getName());
            preparedStatement.setInt(2, cla.getNum());
            preparedStatement.setTimestamp(3, DateUtils.getTimestamp());
            int i = preparedStatement.executeUpdate();
            System.out.println("i = " + i);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }
    }

    private static void query() {
        Connection conn = DBUtils.getConn();
        ArrayList<Cla> list = new ArrayList<>();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = conn.prepareStatement("select * from cla where id = ?");
            preparedStatement.setInt(1, 2);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Cla cla = new Cla();
                cla.setId(resultSet.getInt("id"));
                cla.setName(resultSet.getString("name"));
                cla.setNum(resultSet.getInt("num"));
                Timestamp timestamp = resultSet.getTimestamp("create_time");
                /*
                   java.sql.Timestamp --> java.util.Date
                 */
                cla.setCreateTime(timestamp);
                list.add(cla);
            }
            list.forEach(System.out::println);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}
